package com.example.utils;

import com.example.data.model.User;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;
import java.util.stream.Stream;

/**
 * Created by hldev on 16-12-16.
 */
@Component
public class DemoTokenComponent {

    public void storeAuthTokenToHttpResponse(HttpServletResponse response, AuthToken authToken) {
        Cookie atCookie = createCookieFromAuthToken(authToken);
        setCookie(atCookie);
        response.addCookie(atCookie);
        response.addHeader(DemoCommonConstants.DemoAuthToken, atCookie.getValue());
    }

    public void storeInfoCookieToHttpResponse(HttpServletResponse response, User user) {
        Cookie InfoCookie = createCookieFromUser(user);
        setCookie(InfoCookie);
        InfoCookie.setHttpOnly(true);
        response.addCookie(InfoCookie);
        response.addHeader(DemoCommonConstants.DemoCookie, InfoCookie.getValue());

    }

    private Cookie createCookieFromAuthToken(AuthToken authToken) {
        return new Cookie(DemoCommonConstants.DemoAuthToken, Encrypt.encryptStrWithBase64(authToken.toString()));
    }

    private Cookie createCookieFromUser(User user) {
        return new Cookie(DemoCommonConstants.DemoCookie, user.getId() + "/" + user.getUserName());
    }

    private void setCookie(Cookie cookie) {
        cookie.setHttpOnly(true);
        cookie.setMaxAge(36000);
        cookie.setDomain("localhost");
        cookie.setPath("/");
    }
}
